from django_redis import get_redis_connection
from rest_framework import mixins
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.serializers import Serializer
from rest_framework.views import APIView

from goods.models import SKU
from goods.serializers import SKUSerializer
from users.utils import generic_verify_url, check_active_token


from users.models import User


class RegisterUsernameCountAPIView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        context = {
            'count':count,
            'username':username
        }
        return Response(context)

class RegisterPhoneCountAPIView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        context = {
            'count': count,
            'phone': mobile
        }
        return Response(context)

from rest_framework.generics import CreateAPIView, RetrieveAPIView, \
    UpdateAPIView, GenericAPIView
from .serializers import RegisterCreateSerializer, UserDetailSerializer, \
    EmailSerializer, AddressViewSerializer, AddUserBrowsingHistorySerializer


class RegisterCreateView(CreateAPIView):
    serializer_class = RegisterCreateSerializer

class UserDetailView(RetrieveAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer
    def get_object(self):
        return self.request.user

class EmailView(APIView):


    permission_classes = [IsAuthenticated]

    def put(self, request):

        data = request.data

        user = request.user

        serializer = EmailSerializer(instance=user, data=data)
        serializer.is_valid(raise_exception=True)

        serializer.save()


        from django.core.mail import send_mail

        subject = '美多商场激活邮件'

        message = ''

        from_email = '美多商城<qi_rui_hua@163.com>'

        email = request.data.get('email')
        recipient_list = [email]

        verify_url = generic_verify_url(request.user.id, email)

        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s</a></p>' % (email, verify_url, verify_url)



        from celery_tasks.email.tasks import send_active_email

        send_active_email.delay(subject=subject,
                                message=message,
                                from_email=from_email,
                                recipient_list=recipient_list,
                                html_message=html_message)

        # 4.返回相应
        return Response(serializer.data)





from rest_framework import status


class EmailVerificationAPIView(APIView):
    def get(self, request):
        # 1.接收token
        token = request.query_params.get('token')
        if token is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        data = check_active_token(token)
        if data is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        user_id = data.get('user_id')
        email = data.get('email')

        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        user.email_active = True
        user.save()

        return Response({'msg': 'ok'})

class AddressViewSet(APIView):

    permission_classes = [IsAuthenticated]

    def post(self,request):
        data = request.data
        serializer=AddressViewSerializer(data=data,context={'request':request})
        serializer.is_valid(raise_exception = True)
        serializer.save()
        return  Response(serializer.data)


class UserBrowsingHistoryView(mixins.CreateModelMixin, GenericAPIView):
    """
    用户浏览历史记录
    POST /users/browerhistories/
    GET  /users/browerhistories/
    数据只需要保存到redis中
    """
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]



    def post(self, request):
        """保存"""
        return self.create(request)

    def get(self,request):
        """获取"""
        #获取用户信息
        user_id = request.user.id
        #连接redis
        redis_conn =  get_redis_connection('history')
        #获取数据
        history_sku_ids = redis_conn.lrange('history_%s'%user_id,0,5)
        skus = []
        for sku_id in history_sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            skus.append(sku)
        #序列化
        serializer = SKUSerializer(skus,many=True)
        return Response(serializer.data)

from rest_framework_jwt.views import ObtainJSONWebToken
from carts.utils import merge_cart_cookie_to_redis

class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):
        # 调用jwt扩展的方法，对用户登录的数据进行验证
        response = super().post(request)

        # 如果用户登录成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登录成功
            user = serializer.validated_data.get("user")
            # 合并购物车
            #merge_cart_cookie_to_redis(request, user, response)
            response = merge_cart_cookie_to_redis(request, user, response)

        return response

